import Linkify from "linkify-react";

const { shellService } = window.service;

import logger from "@shared/logger/renderer-logger";

interface LinkifiedTextProps {
  text: string;
}

export function LinkifiedText({ text }: LinkifiedTextProps) {
  const handleLinkClick = (href: string) => {
    logger.debug("Opening external link", { href });
    shellService.openExternal(href);
  };

  // 验证URL是否为有效链接
  const validateUrl = (value: string, type: string) => {
    if (type === "url") {
      try {
        new URL(value.startsWith("http") ? value : `http://${value}`);
        return true;
      } catch (_error) {
        return false;
      }
    }
    return false;
  };

  // 处理换行符，将文本分割成行并保留换行和空格
  const renderTextWithLineBreaks = (text: string) => {
    const lines = text.split("\n");
    return lines.map((line, index) => (
      <span
        key={`line-${index}-${line.slice(0, 10)}`}
        style={{ whiteSpace: "pre-wrap" }}
      >
        <Linkify
          options={{
            validate: validateUrl,
            render({ attributes, content }) {
              return (
                <a
                  href={attributes.href}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="cursor-pointer font-medium hover:underline"
                  onClick={(e) => {
                    e.preventDefault();
                    handleLinkClick(attributes.href);
                  }}
                >
                  {content}
                </a>
              );
            },
          }}
        >
          {line}
        </Linkify>
        {index < lines.length - 1 && <br />}
      </span>
    ));
  };

  return <>{renderTextWithLineBreaks(text)}</>;
}
